// 基础路径
axios.defaults.baseURL="http://localhost:8080"
// 全局配置
Vue.prototype.$http=axios



// 1.axios前置拦截器：每次通过axios发送请求之前，让所有的请求都携带token
axios.interceptors.request.use(config=> {
    // 从localStorage中获取token
    let token = localStorage.getItem("token");
    // 如果有值，将token设置到请求头
    if (token) {
        config.headers['token'] = token;
    }
    return config;
},error => {
    Promise.reject(error);
})

// 2.axios后置拦截器：后端处理完axios请求之后，处理响应的数据
axios.interceptors.response.use(res=>{
    if (false === res.data.success && "noLogin" === res.data.msg) {
        localStorage.removeItem("token");
        localStorage.removeItem("logininfo");
        //router.push({path: '/login'});  // vue语法
        location.href = "login.html";  // 原生HTML语法
        alert("请先登陆！");
    }
    if (false === res.data.success && "timeout" === res.data.msg) {
        localStorage.removeItem("token");
        localStorage.removeItem("logininfo");
        location.href = "login.html";
        alert("登陆过期!");
    }
    return res;
},error => {
    Promise.reject(error);
})

// 3.静态资源拦截器：拦截不发送axios请求的页面【登录之后才能访问】
let url = location.href;
if (url.indexOf("login.html") == -1
    && url.indexOf("register.html") == -1
    && url.indexOf("binder.html") == -1
    && url.indexOf("callback.html") == -1
    && url.indexOf("test") == -1  // 测试的全放行
    ){
    var logininfoStr = localStorage.getItem("logininfo");
    if (!logininfoStr){
        // logininfoStr无值，说明未登陆，跳转到登陆
        location.href = "login.html";
    }
}

// 封装公用方法 - 将url字符串的参数解析为json对象
function parseUrlParams2Obj(url) {
    // http://bugtracker.itsource.cn/callback.html?code=071ZmSkl2Qmjy94oL0ol2XaVXr4ZmSkA&state=1
    let paramStr = url.substring(url.indexOf("?")+1);  // code=071ZmSkl2Qmjy94oL0ol2XaVXr4ZmSkA&state=1
    let paramArr = paramStr.split("&");  // [0]code=071ZmSkl2Qmjy94oL0ol2XaVXr4ZmSkA [1]state=1
    let paramObj = {};
    for(let i = 0;i<paramArr.length;i++){
        let paramTemp = paramArr[i];
        let paramName = paramTemp.split("=")[0];  // code
        let paramValue= paramTemp.split("=")[1];  // 071ZmSkl2Qmjy94oL0ol2XaVXr4ZmSkA
        paramObj[paramName] = paramValue;
    }
    return paramObj;
}